Golang : Output or print out JSON stream/encoded data
Problem :
You need to produce JSON stream or JSON encoded data to web browser or client. How to do that?
Solution :
Set the header Content-Type
to application/json
and write the http.ResponseWriter.
For example :
package main
import (
"net/http"
)
func Employees(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
// NOTE : put jsonStr in a FOR loop to read forever from database and encode the data with
// json.Marshal() function to produce JSON stream
// see https://www.socketloop.com/tutorials/golang-convert-csv-data-to-json-format-and-save-to-file
// for this example, we will use static JSON string
jsonStr := `[{"Name":"Dennis","Age":16,"Job":"CEO"},
{"Name":"Eva","Age":34,"Job":"CFO"},
{"Name":"Paul","Age":28,"Job":"COO"}]`
// output to web or client
w.Write([]byte(jsonStr))
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", Employees)
http.ListenAndServe(":8080", mux)
}
Reference :
https://www.socketloop.com/tutorials/golang-unmarshal-json-from-http-response
See also : Golang : Unmarshal JSON from http response
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+41k Golang : How to check if a string contains another sub-string?
+27.6k PHP : Convert(cast) string to bigInt
+8.4k Golang : Convert word to its plural form example
+22.2k Golang : Convert seconds to minutes and remainder seconds
+29.5k Golang : Login(Authenticate) with Facebook example
+12.3k Golang : Flush and close file created by os.Create and bufio.NewWriter example
+12.6k Golang : Get absolute path to binary for os.Exec function with exec.LookPath
+6.8k Unix/Linux : How to fix CentOS yum duplicate glibc or device-mapper-libs dependency error?
+41.9k Golang : How do I convert int to uint8?
+9.8k Golang : Qt get screen resolution and display on center example
+8.3k Golang : Implementing class(object-oriented programming style)
+11k Golang : Generate random elements without repetition or duplicate